<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <button @click="$router.back()" class="mr-4 p-2 text-gray-500 hover:text-gray-700 focus:outline-none">
          <ArrowLeftIcon class="h-6 w-6" />
        </button>
        <h2 class="text-2xl font-semibold text-gray-800">
          {{ isEdit ? '编辑设备' : '设备登记' }}
        </h2>
      </div>
    </div>

    <div class="max-w-4xl mx-auto">
      <div class="bg-white rounded-xl shadow-lg p-6">
        <form @submit.prevent="handleSubmit" class="space-y-6">
          <!-- 基本信息 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">基本信息</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label for="code" class="block text-sm font-medium text-gray-700">设备编号 *</label>
                <input
                  type="text"
                  id="code"
                  v-model="form.code"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入设备编号"
                />
                <p v-if="errors.code" class="mt-1 text-sm text-red-600">{{ errors.code }}</p>
              </div>

              <div>
                <label for="name" class="block text-sm font-medium text-gray-700">设备名称 *</label>
                <input
                  type="text"
                  id="name"
                  v-model="form.name"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入设备名称"
                />
                <p v-if="errors.name" class="mt-1 text-sm text-red-600">{{ errors.name }}</p>
              </div>

              <div>
                <label for="category" class="block text-sm font-medium text-gray-700">设备类别 *</label>
                <select
                  id="category"
                  v-model="form.category"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                >
                  <option value="">请选择设备类别</option>
                  <option value="计算机设备">计算机设备</option>
                  <option value="实验仪器">实验仪器</option>
                  <option value="化学仪器">化学仪器</option>
                  <option value="生物仪器">生物仪器</option>
                  <option value="其他设备">其他设备</option>
                </select>
                <p v-if="errors.category" class="mt-1 text-sm text-red-600">{{ errors.category }}</p>
              </div>

              <div>
                <label for="status" class="block text-sm font-medium text-gray-700">设备状态 *</label>
                <select
                  id="status"
                  v-model="form.status"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                >
                  <option value="">请选择设备状态</option>
                  <option value="NORMAL">正常</option>
                  <option value="BORROWED">借用中</option>
                  <option value="REPAIRING">维修中</option>
                  <option value="SCRAPPED">已报废</option>
                </select>
                <p v-if="errors.status" class="mt-1 text-sm text-red-600">{{ errors.status }}</p>
              </div>
            </div>
          </div>

          <!-- 规格信息 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">规格信息</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div class="md:col-span-2">
                <label for="specification" class="block text-sm font-medium text-gray-700">规格型号</label>
                <textarea
                  id="specification"
                  v-model="form.specification"
                  rows="3"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入设备规格型号"
                ></textarea>
                <p v-if="errors.specification" class="mt-1 text-sm text-red-600">{{ errors.specification }}</p>
              </div>

              <div>
                <label for="quantity" class="block text-sm font-medium text-gray-700">数量 *</label>
                <input
                  type="number"
                  id="quantity"
                  v-model.number="form.quantity"
                  required
                  min="1"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入数量"
                />
                <p v-if="errors.quantity" class="mt-1 text-sm text-red-600">{{ errors.quantity }}</p>
              </div>

              <div>
                <label for="unitPrice" class="block text-sm font-medium text-gray-700">单价 (元) *</label>
                <input
                  type="number"
                  id="unitPrice"
                  v-model.number="form.unitPrice"
                  required
                  min="0"
                  step="0.01"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入单价"
                />
                <p v-if="errors.unitPrice" class="mt-1 text-sm text-red-600">{{ errors.unitPrice }}</p>
              </div>
            </div>
          </div>

          <!-- 采购信息 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">采购信息</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label for="manufacturer" class="block text-sm font-medium text-gray-700">生产厂家</label>
                <input
                  type="text"
                  id="manufacturer"
                  v-model="form.manufacturer"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入生产厂家"
                />
                <p v-if="errors.manufacturer" class="mt-1 text-sm text-red-600">{{ errors.manufacturer }}</p>
              </div>

              <div>
                <label for="purchaseDate" class="block text-sm font-medium text-gray-700">购置日期 *</label>
                <input
                  type="date"
                  id="purchaseDate"
                  v-model="form.purchaseDate"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                />
                <p v-if="errors.purchaseDate" class="mt-1 text-sm text-red-600">{{ errors.purchaseDate }}</p>
              </div>

              <div>
                <label for="warranty" class="block text-sm font-medium text-gray-700">保修期</label>
                <input
                  type="text"
                  id="warranty"
                  v-model="form.warranty"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="如：3年、12个月等"
                />
                <p v-if="errors.warranty" class="mt-1 text-sm text-red-600">{{ errors.warranty }}</p>
              </div>

              <div>
                <label for="handler" class="block text-sm font-medium text-gray-700">经手人</label>
                <input
                  type="text"
                  id="handler"
                  v-model="form.handler"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入经手人"
                />
                <p v-if="errors.handler" class="mt-1 text-sm text-red-600">{{ errors.handler }}</p>
              </div>

              <div>
                <label for="laboratoryId" class="block text-sm font-medium text-gray-700">所属实验室 *</label>
                <select
                  id="laboratoryId"
                  v-model="form.laboratoryId"
                  required
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                >
                  <option value="">请选择实验室</option>
                  <option v-for="lab in laboratories" :key="lab.id" :value="lab.id">
                    {{ lab.name }}
                  </option>
                </select>
                <p v-if="errors.laboratoryId" class="mt-1 text-sm text-red-600">{{ errors.laboratoryId }}</p>
              </div>
            </div>
          </div>

          <!-- 其他信息 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">其他信息</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label for="serialNumber" class="block text-sm font-medium text-gray-700">序列号</label>
                <input
                  type="text"
                  id="serialNumber"
                  v-model="form.serialNumber"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入序列号"
                />
                <p v-if="errors.serialNumber" class="mt-1 text-sm text-red-600">{{ errors.serialNumber }}</p>
              </div>

              <div>
                <label for="location" class="block text-sm font-medium text-gray-700">存放位置</label>
                <input
                  type="text"
                  id="location"
                  v-model="form.location"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入存放位置"
                />
                <p v-if="errors.location" class="mt-1 text-sm text-red-600">{{ errors.location }}</p>
              </div>

              <div class="md:col-span-2">
                <label for="description" class="block text-sm font-medium text-gray-700">设备描述</label>
                <textarea
                  id="description"
                  v-model="form.description"
                  rows="3"
                  class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="请输入设备描述"
                ></textarea>
                <p v-if="errors.description" class="mt-1 text-sm text-red-600">{{ errors.description }}</p>
              </div>
            </div>
          </div>

          <!-- 设备图片 -->
          <div>
            <h3 class="text-lg font-medium text-gray-900 mb-4">设备图片</h3>
            <div class="border-2 border-dashed border-gray-300 rounded-lg p-6">
              <div class="text-center">
                <PhotoIcon class="mx-auto h-12 w-12 text-gray-400" />
                <div class="mt-4">
                  <label for="image" class="cursor-pointer">
                    <span class="mt-2 block text-sm font-medium text-gray-900">
                      点击上传设备图片
                    </span>
                    <input
                      id="image"
                      type="file"
                      accept="image/*"
                      @change="handleImageUpload"
                      class="sr-only"
                    />
                  </label>
                  <p class="mt-1 text-xs text-gray-500">
                    支持 PNG, JPG, GIF 格式，最大 5MB
                  </p>
                </div>
              </div>
              <div v-if="form.imageUrl" class="mt-4">
                <img :src="form.imageUrl" :alt="form.name" class="mx-auto h-32 w-32 object-cover rounded-lg">
                <button
                  type="button"
                  @click="removeImage"
                  class="mt-2 text-sm text-red-600 hover:text-red-800"
                >
                  删除图片
                </button>
              </div>
            </div>
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end space-x-3 pt-6 border-t border-gray-200">
            <button
              type="button"
              @click="$router.back()"
              class="px-6 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              取消
            </button>
            <button
              type="submit"
              :disabled="loading"
              class="px-6 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {{ loading ? '保存中...' : (isEdit ? '更新设备' : '登记设备') }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeftIcon, PhotoIcon } from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const isEdit = computed(() => !!route.params.id)

const form = reactive({
  code: '',
  name: '',
  category: '',
  status: '',
  specification: '',
  quantity: 1,
  unitPrice: 0,
  manufacturer: '',
  purchaseDate: '',
  warranty: '',
  handler: '',
  serialNumber: '',
  location: '',
  description: '',
  imageUrl: '',
  laboratoryId: null
})

const errors = reactive({})
const laboratories = ref([])

// 验证表单
const validateForm = () => {
  // 清空之前的错误
  Object.keys(errors).forEach(key => delete errors[key])
  
  let isValid = true

  if (!form.code.trim()) {
    errors.code = '请输入设备编号'
    isValid = false
  }

  if (!form.name.trim()) {
    errors.name = '请输入设备名称'
    isValid = false
  }

  if (!form.category) {
    errors.category = '请选择设备类别'
    isValid = false
  }

  if (!form.status) {
    errors.status = '请选择设备状态'
    isValid = false
  }

  if (!form.laboratoryId) {
    errors.laboratoryId = '请选择所属实验室'
    isValid = false
  }

  if (!form.quantity || form.quantity <= 0) {
    errors.quantity = '请输入有效的数量'
    isValid = false
  }

  if (!form.unitPrice || form.unitPrice < 0) {
    errors.unitPrice = '请输入有效的单价'
    isValid = false
  }

  if (!form.purchaseDate) {
    errors.purchaseDate = '请选择购置日期'
    isValid = false
  }

  return isValid
}

// 处理图片上传
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 检查文件大小
    if (file.size > 5 * 1024 * 1024) {
      showMessage('图片大小不能超过5MB', 'error')
      return
    }

    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      showMessage('请选择图片文件', 'error')
      return
    }

    // 创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      form.imageUrl = e.target.result
    }
    reader.readAsDataURL(file)
  }
}

// 删除图片
const removeImage = () => {
  form.imageUrl = ''
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  try {
    loading.value = true
    
    // 构建请求数据
    const requestData = {
      code: form.code,
      name: form.name,
      category: form.category,
      specification: form.specification,
      unitPrice: form.unitPrice,
      quantity: form.quantity,
      purchaseDate: form.purchaseDate,
      manufacturer: form.manufacturer,
      warrantyPeriod: form.warranty,
      handlerName: form.handler,
      laboratoryId: form.laboratoryId,
      location: form.location,
      status: form.status,
      remark: form.description
    }
    
    if (isEdit.value) {
      // 更新设备
      await request.put(`/equipment/${route.params.id}`, requestData)
      showMessage('设备更新成功', 'success')
    } else {
      // 创建设备
      await request.post('/equipment', requestData)
      showMessage('设备登记成功', 'success')
    }
    
    router.push('/equipment')
    
  } catch (error) {
    console.error('保存设备失败:', error)
    showMessage('保存设备失败', 'error')
  } finally {
    loading.value = false
  }
}

// 加载实验室列表
const loadLaboratories = async () => {
  try {
    const response = await request.get('/laboratories/list?page=1&size=100')
    laboratories.value = response.data.records || []
  } catch (error) {
    console.error('加载实验室列表失败:', error)
    showMessage('加载实验室列表失败', 'error')
  }
}

// 加载设备信息（编辑模式）
const loadEquipment = async () => {
  if (!isEdit.value) return

  try {
    loading.value = true
    const equipmentId = route.params.id
    
    // 调用真实API加载设备信息
    const response = await request.get(`/equipment/${equipmentId}`)
    const equipment = response.data
    
    // 映射API数据到表单字段
    form.code = equipment.code || ''
    form.name = equipment.name || ''
    form.category = equipment.category || ''
    form.status = equipment.status || 'NORMAL'
    form.specification = equipment.specification || ''
    form.quantity = equipment.quantity || 1
    form.unitPrice = equipment.unitPrice || 0
    form.manufacturer = equipment.manufacturer || ''
    form.purchaseDate = equipment.purchaseDate || ''
    form.warranty = equipment.warranty || ''
    form.handlerName = equipment.handlerName || ''
    form.serialNumber = equipment.serialNumber || ''
    form.location = equipment.location || ''
    form.note = equipment.note || ''
    form.laboratoryId = equipment.laboratoryId || ''
    
  } catch (error) {
    console.error('加载设备信息失败:', error)
    showMessage('加载设备信息失败', 'error')
  } finally {
    loading.value = false
  }
}

// 简单消息显示函数
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadLaboratories()
  loadEquipment()
})
</script>